const logger = require('../../util/logger');

class Store {
  
  constructor(init = true) {
    if (init) {
      this.sessions = new Map();
      this._timer = new Map();
    }
  }
  
  get(sid) {
    if (!this.sessions.has(sid)) return undefined;
    return this.sessions.get(sid);
  }
  
  set(sid, session) {
    if (this.sessions.has(sid) && this._timer.has(sid)) {
      const timeout = this._timer.get(sid);
      if (timeout) clearTimeout(timeout);
    }
    
    if (session.cookie.maxAge) {
      this._timer.set(sid, setTimeout(() => this.destroy(sid), session.cookie.maxAge));
    }
    try {
      this.sessions.set(sid, session);
    } catch (err) {
      logger.log('Set session error:', err);
    }
    return sid;
  }
  
  destroy(sid) {
    this.sessions.delete(sid);
    this._timer.delete(sid);
  }
}

module.exports = Store;
